/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var sendReq = getXmlHttpRequestObject();
var receiveReq = getXmlHttpRequestObject();
var xmlResponse;
var lastMessageCount = [];

function $(id) {
    return document.getElementById(id);
}

function initChat() {
    receive();
}

function newChat(username) {
    if ($("chatbox_"+username)!=null) {
        inactivate();
        $("chatbox_"+username).setAttribute("class", "chat_people_active");
    }
    else {
        inactivate();
        var newChat = document.createElement('span');
        newChat.setAttribute("class", "chat_people_active");
        newChat.setAttribute("id", "chatbox_"+username);
        $("chat_group").appendChild(newChat);

        var newChatMessage = document.createElement('div');
        newChatMessage.setAttribute("class", "chat_message");
        newChat.appendChild(newChatMessage);

        var newChatInput = document.createElement('div');
        newChatInput.setAttribute("class", "chat_input");
        newChat.appendChild(newChatInput);

        var newChatName = document.createElement('div');
        newChatName.setAttribute("class", "chat_name");
        newChatName.setAttribute("onclick", "toogleShow(this.parentNode)");
        newChat.appendChild(newChatName);

        var newInputBox = document.createElement('input');
        newInputBox.setAttribute("type", "text");
        newInputBox.setAttribute("name", username);
        newInputBox.setAttribute("onkeypress", "chatInputHandler(event,this)");
        newChatInput.appendChild(newInputBox);

        var newChatUsername = document.createElement('span');
        newChatUsername.setAttribute("class", "chat_username");
        newChatUsername.innerHTML = username;
        newChatName.appendChild(newChatUsername);

        var newChatClose = document.createElement('span');
        newChatClose.setAttribute("class", "chat_close");
        newChatClose.setAttribute("onclick", "closeChat(this.parentNode.parentNode)");
        newChatClose.innerHTML = "x";
        newChatName.appendChild(newChatClose);
        
        newInputBox.focus();
    }
}

function closeChat(object) {
    $("chat_group").removeChild(object);
}

function inactivate() {
    var activeChat = document.getElementsByClassName("chat_people_active");
    if (activeChat[0]!=null) {
        activeChat[0].setAttribute("class", "chat_people_inactive");
    }
}

function toogleShow(object) {
    if (object.className == "chat_list_active") {
        object.setAttribute("class", "chat_list_inactive");
    }
    else if (object.className == "chat_list_inactive") {
        object.setAttribute("class", "chat_list_active");
    }
    else if (object.className == "chat_people_active") {
        inactivate();
        object.setAttribute("class", "chat_people_inactive");
    }
    else if (object.className == "chat_people_inactive") {
        inactivate();
        object.setAttribute("class", "chat_people_active");
    }
    if (object.getElementsByTagName("input")[0]!=null) object.getElementsByTagName("input")[0].focus();
}

function chatInputHandler(e, object) {
    var key = e.keyCode || e.which;
    if (key == 13 && object.value.ltrim()!="") {
        send(object.name, object.value.ltrim());
        object.value = "";
    }
}

function send(username, message) {
    // fungsi untuk kirim chat via ajax
    sendReq.open("GET","ajax/send_chat.php?to="+username+"&message="+message,true);
    sendReq.send();
}

function receive() {
    // fungsi untuk menerima message via ajax
    receiveReq.open("GET","ajax/receive_chat.php",true);
    receiveReq.send();

    receiveReq.onreadystatechange=function()
    {
        if (receiveReq.readyState==4 && receiveReq.status==200)
        {
            //alert(receiveReq.responseText);
            xmlResponse = receiveReq.responseXML;
            parseXML(xmlResponse);
            setTimeout('receive();',2000);
        }
    }
}

function parseXML(objXML) {
    var currentUsername     = objXML.getElementsByTagName("cuser")[0].childNodes[0].nodeValue;
    var listObject          = objXML.getElementsByTagName("package");
    var currMessageCount    = [];

    // mengeset nilai ke 0
    for (i=0;i<listObject.length;i++){
        if (getInfoXML(listObject,i,"from")==currentUsername) {
            if (currMessageCount[getInfoXML(listObject,i,"to")] != 0) currMessageCount[getInfoXML(listObject,i,"to")] = 0;
            if (lastMessageCount[getInfoXML(listObject,i,"to")] == null) lastMessageCount[getInfoXML(listObject,i,"to")] = 0;
        }
        else {
            if (currMessageCount[getInfoXML(listObject,i,"from")] != 0) currMessageCount[getInfoXML(listObject,i,"from")] = 0;
            if (lastMessageCount[getInfoXML(listObject,i,"from")] == null) lastMessageCount[getInfoXML(listObject,i,"from")] = 0;
        }
    }

    // menghitung jumlah pesan terlebih dahulu
    for (i=0;i<listObject.length;i++){
        if (getInfoXML(listObject,i,"from")==currentUsername) {
                currMessageCount[getInfoXML(listObject,i,"to")]++;
        }
        else {
                currMessageCount[getInfoXML(listObject,i,"from")]++;
        }
    }

    // menghapus pesan yang sebelumnya telah ada
    for (i=0;i<listObject.length;i++){
        if (currMessageCount[getInfoXML(listObject,i,"to")] != lastMessageCount[getInfoXML(listObject,i,"to")]) {
            if ($("chatbox_"+getInfoXML(listObject,i,"to"))!=null) {
                $("chatbox_"+getInfoXML(listObject,i,"to")).getElementsByClassName("chat_message")[0].innerHTML = "";
            }
        }
        if (currMessageCount[getInfoXML(listObject,i,"from")] != lastMessageCount[getInfoXML(listObject,i,"from")]) {
            if ($("chatbox_"+getInfoXML(listObject,i,"from"))!=null) {
                $("chatbox_"+getInfoXML(listObject,i,"from")).getElementsByClassName("chat_message")[0].innerHTML = "";
            }
        }
    }

    for (i=0;i<listObject.length;i++){
        if (getInfoXML(listObject,i,"from")==currentUsername) {
            if (currMessageCount[getInfoXML(listObject,i,"to")] != lastMessageCount[getInfoXML(listObject,i,"to")]) {
                if ($("chatbox_"+getInfoXML(listObject,i,"to"))==null) {
                    newChat(getInfoXML(listObject,i,"to"));
                }
                addChatMessage(getInfoXML(listObject,i,"to"), "<b>"+currentUsername+"</b>: "+getInfoXML(listObject,i,"message"))
            }
        }
        else {
            if (currMessageCount[getInfoXML(listObject,i,"from")] != lastMessageCount[getInfoXML(listObject,i,"from")]) {
                if ($("chatbox_"+getInfoXML(listObject,i,"from"))==null) {
                    newChat(getInfoXML(listObject,i,"from"));
                }
                addChatMessage(getInfoXML(listObject,i,"from"), "<b>"+getInfoXML(listObject,i,"from")+"</b>: "+getInfoXML(listObject,i,"message"))
            }
        }
    }

    for (i in currMessageCount) {
        lastMessageCount[i] = currMessageCount[i];
    }
}

function addChatMessage(username,message) {
    $("chatbox_"+username).getElementsByClassName("chat_message")[0].innerHTML += message+"<br/>";
}

function getInfoXML(listObject,i,tagname) {
    return listObject[i].getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
